import { type Model } from 'mongoose';
import { Article, ArticleDocument, CreateArticleDto, UpdateArticleDto } from '@ai/entity';
import { Injectable, OnModuleInit } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { ArticleCategoryService } from '../article-category/article-category.service';

@Injectable()
export class ArticleService implements OnModuleInit {
    constructor(@InjectModel(Article.name) private readonly articleModel: Model<ArticleDocument>) {}

    onModuleInit() {
        this.articleModel.init();
    }

    create(createArticleDto: CreateArticleDto) {
        return this.articleModel.create(createArticleDto);
    }

    findAll(updateArticleDto: UpdateArticleDto = {}) {
        return this.articleModel
            .find(updateArticleDto)
            .populate('authors', '', 'User')
            .populate('category', '', 'ArticleCategory')
            .exec();
    }

    findOne(updateArticleDto: UpdateArticleDto = {}) {
        return this.articleModel
            .findOne(updateArticleDto)
            .populate('authors', '', 'User')
            .populate('category', '', 'ArticleCategory')
            .exec();
    }

    findById(id: string) {
        return this.articleModel
            .findById(id)
            .populate('authors', '', 'User')
            .populate('category', '', 'ArticleCategory')
            .exec();
    }

    async getAllCategories() {
        const ret = await this.articleModel.aggregate().group({ _id: 1, categories: { $addToSet: '$category' } });
        return [].concat(ret?.[0]?.categories).filter(Boolean);
    }

    update(id: string, updateArticleDto: UpdateArticleDto) {
        return this.articleModel.findByIdAndUpdate(id, updateArticleDto, { new: true });
    }

    remove(id: string) {
        return this.articleModel.findByIdAndDelete(id);
    }
}
